<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
    :size="formSize"
    status-icon
  >
    <el-form-item label="用户名：" prop="Name">
      <el-input
        v-model="ruleForm.Name"
        placeholder="请输入用户名"
        style="width: 240px"
      />
    </el-form-item>
    <el-form-item label="密码：" prop="Pwd">
      <el-input
        v-model="ruleForm.Pwd"
        placeholder="请输入密码"
        style="width: 240px"
        type="password"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)">
        登录
      </el-button>
      <el-button @click="resetForm(ruleFormRef)">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue';
import {
  ElMessage,
  type ComponentSize,
  type FormInstance,
  type FormRules
} from 'element-plus';
import axiosInstance from "@/stores/Utils/axiosHelp"
import { useCounterStore } from '@/stores/counter';
import { useRouter } from 'vue-router';

const router = useRouter();
const useStore = useCounterStore();

interface RuleForm {
  Name: string;
  Pwd: string;
}

const formSize = ref<ComponentSize>('default');
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  Name: '',
  Pwd: ''
});

const rules = reactive<FormRules<RuleForm>>({
  Name: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
  Pwd: [{ required: true, message: '密码不能为空', trigger: 'blur' }]
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      axiosInstance.get('/api/User/UserLogin',{
          params:{
            Name:ruleForm.Name,
            Pwd:ruleForm.Pwd
          }
        })
        .then((res) => {
            console.log(res)
          if (res.isSuccess) {
            ElMessage.success('登录成功');

            useStore.userinfo.id = res.data.id;
            useStore.userinfo.name = res.data.name;
            useStore.userinfo.token = res.data.token;

            localStorage.setItem('token', res.data.Token);

            router.push('MenuView');
          } else {
            ElMessage.error(res.data.message);
          }
        });
    } else {
      console.log('error submit!', fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>../../stores/Utils/axiosHelp
